/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: pointcloud_to_pcd.cpp 33238 2010-03-11 00:46:58Z rusu $
 *
 */

// ROS core
#include <ros/ros.h>
#include <cmath> 
#include <math.h>

#include <iostream>
#include <sensor_msgs/PointCloud2.h>


// PCL includes
#include <pcl/common/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>

#include <pcl_conversions/pcl_conversions.h>

#include <Eigen/Geometry>

// STL
#include <string>

/**
\author Radu Bogdan Rusu
@b pointcloud_to_pcd is a simple node that retrieves a ROS point cloud message and saves it to disk into a PCD (Point
Cloud Data) file format.
**/
class PointCloudToPCD
{
protected:
  ros::NodeHandle nh_;

private:
  std::string prefix_;
  std::string postfix_;
  bool binary_;
  bool compressed_;
  int64_t last_save_time_=0;
  std::string fixed_frame_;
  pcl::PCDWriter writer_;
public:
  std::string cloud_topic_;
  std::string save_dir_;

  ros::Subscriber sub_;

  ////////////////////////////////////////////////////////////////////////////////
  // Callback
  void
  cloud_cb(const boost::shared_ptr<const pcl::PCLPointCloud2> & cloud)
  {
    std::stringstream ss;

    int64_t timestamp = cloud->header.stamp;
    // std::cout<<"timestamp "<<timestamp<<std::endl;
    int64_t timestamp_floor = int64_t(cloud->header.stamp/1000000)*1000000;
    int64_t second_fraction = timestamp - timestamp_floor;
    int64_t save_name;

    if (second_fraction>=0 && second_fraction < 500000)
    {
      save_name = timestamp_floor + 250000;
    } else
    {
      save_name = timestamp_floor+750000;
    }
    ss << prefix_ << std::to_string(save_name)<<"_"<<postfix_<< ".pcd";

    int64_t time_diff = abs(timestamp - save_name);
    // std::cout<<"save name "<<save_name<<std::endl;
    // std::cout<<"time diff "<<time_diff<<std::endl;
    // std::cout<<"last time diff "<<abs(save_name - last_save_time_)<<std::endl;
    if (time_diff > abs(save_name - last_save_time_) || time_diff > 65000)
    {
      return;
    }

    last_save_time_ = timestamp;

    // ROS_INFO("Data saved to %s", ss.str().c_str());

    pcl::PointCloud<pcl::PointXYZI>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZI>);
    pcl::fromPCLPointCloud2(*cloud, *cloud1);

    // writer_.writeBinary(ss.str(), *cloud);
    pcl::io::savePCDFileBinary(ss.str(), *cloud1);
  }

  ////////////////////////////////////////////////////////////////////////////////
  PointCloudToPCD()
  {
    // Check if a prefix parameter is defined for output file names.
    ros::NodeHandle priv_nh("~");
    if (priv_nh.getParam("prefix", prefix_)) {
      ROS_INFO_STREAM("PCD file prefix is: " << prefix_);
    } else if (nh_.getParam("prefix", prefix_)) {
      ROS_WARN_STREAM(
        "Non-private PCD prefix parameter is DEPRECATED: " <<
          prefix_);
    }
    if (priv_nh.getParam("postfix", postfix_)) {
      ROS_INFO_STREAM("PCD file postfix is: " << postfix_);
    } else if (nh_.getParam("postfix", postfix_)) {
      ROS_WARN_STREAM(
        "Non-private PCD postfix parameter is DEPRECATED: " <<
          postfix_);
    }

    cloud_topic_ = "lidarinput";

    sub_ = nh_.subscribe(cloud_topic_, 50, &PointCloudToPCD::cloud_cb, this);
    ROS_INFO(
      "Listening for incoming data on topic %s",
      nh_.resolveName(cloud_topic_).c_str());
  }
};

/* ---[ */
int
main(int argc, char ** argv)
{
  ros::init(argc, argv, "save_lidar", ros::init_options::AnonymousName);

  PointCloudToPCD b;
  ros::spin();

  return 0;
}
/* ]--- */
